package com.jorado.httpclient;

import com.jorado.json.JsonUtils;

import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;

/**
 * @Auther: len.zhang
 * @Date: 2019/6/14 16:40
 * @Description:
 */
public class HttpResponseParser {

    private HttpResponse response;

    public HttpResponseParser(HttpResponse response) {
        this.response = response;
    }

    public String getBody() {
        String body = response.getBody();
        return body;
    }

    public <T> T from(Class<T> t) {

        String body = response.getBody();

        //确认输出类型
        MediaType mediaType = MediaType.parse(response.getContentType());

        if (mediaType == MediaType.JSON) {
            return fromJson(t);
        }

        if (mediaType == MediaType.XML) {
            return fromXml(t);
        }

        return (T) body;
    }

    public <T> T fromJson(Class<T> t) {
        String body = response.getBody();
        return JsonUtils.fromJson(body, t);
    }

    public <T> T fromXml(Class<T> t) {
        String body = response.getBody();
        ByteArrayInputStream in = new ByteArrayInputStream(body.getBytes());
        XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(in));
        decoder.close();
        return (T) decoder.readObject();
    }
}
